package com.kaizeli.website.exception;

import com.kaizeli.website.response.Result;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@ConditionalOnProperty(name = "app.exception.advice-enabled", havingValue = "true", matchIfMissing = false)
public class GlobalExceptionHandler {

    // 捕获自定义登录异常
    @ExceptionHandler(LoginException.class)
    public Result<?> handleLoginException(LoginException ex) {
        return new Result<>(401, ex.getMessage(), null);
    }

    // 捕获自定义权限异常
    @ExceptionHandler(NoPermissionException.class)
    public Result<?> handleNoPermissionException(NoPermissionException ex) {
        return new Result<>(403, ex.getMessage(), null);
    }

    // 捕获用户名已存在异常
    @ExceptionHandler(UsernameAlreadyExistsException.class)
    public Result<?> handleUsernameAlreadyExists(UsernameAlreadyExistsException ex) {
        return new Result<>(400, ex.getMessage(), null);
    }
    // 捕获用户不存在异常
    @ExceptionHandler(UserNotFoundException.class)
    public Result<?> handleUserNotFound(UserNotFoundException ex) {
        return new Result<>(404, ex.getMessage(), null);
    }

    // 捕获不能删除管理员异常
    @ExceptionHandler(CannotDeleteAdminException.class)
    public Result<?> handleCannotDeleteAdmin(CannotDeleteAdminException ex) {
        return new Result<>(400, ex.getMessage(), null);
    }



    // 捕获所有 RuntimeException
    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleRuntimeException(RuntimeException ex) {
        return new Result<>(500, "服务器内部错误: " + ex.getMessage(), null);
    }

    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException ex) {
        return Result.error(Integer.parseInt(ex.getCode()), ex.getMessage());
    }


}
